<?php

namespace PhpYes\Com;


class RedisCache implements CacheInterface
{
    /** @var array */
    private static $name2RedisCacheArr;

    /** @var \Redis */
    private $redis;

    /**
     * @param string $name
     * @return null|RedisCache
     * @throws HttpException
     */
    public static function getRedisCache($name)
    {
        $name = empty($name) ? null : trim($name);
        if (empty($name)) {
            return null;
        }

        if (empty(self::$name2RedisCacheArr[$name])) {
            $redis = RedisManager::getSingleObj()->getRedis($name);
            if (empty($redis)) {
                return null;
            }

            self::$name2RedisCacheArr[$name] = new RedisCache($redis);
        }

        return self::$name2RedisCacheArr[$name];
    }

    /**
     * RedisCache constructor.
     * @param \Redis $redis
     */
    public function __construct($redis)
    {
        $this->redis = $redis;
    }

    /**
     * @return \Redis
     */
    public function getRedis()
    {
        return $this->redis;
    }

    /**
     * @param string $key
     * @return string
     */
    public function get($key)
    {
        return $this->redis->get($key);
    }

    /**
     * Remove specified keys.
     *
     * @param   int|array $key An array of keys, or an undefined number of parameters, each a key: key1 key2 key3 ... keyN
     * @return int - Number of keys deleted.
     */
    public function del($key)
    {
        return $this->redis->del($key);
    }

    /**
     * @param string $key
     * @param int $ttl - seconds, time to live
     * @param string $val
     * @return bool
     */
    public function set($key, $ttl, $val)
    {
        return $this->redis->setex($key, $ttl, $val);
    }

}